<template>
  <div class="data-table">
    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item>
          <el-select v-model="filterForm.province" placeholder="省份" clearable @change="handleProvinceChange">
            <el-option
              v-for="item in provinces"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.city" placeholder="城市" clearable @change="handleCityChange">
            <el-option
              v-for="item in cities"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.district" placeholder="区县" clearable @change="handleDistrictChange">
            <el-option
              v-for="item in districts"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.companyType" placeholder="竞品名称" clearable @change="handleCompanyTypeChange">
            <el-option
              v-for="item in companyTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.projectType" placeholder="我司竞品参项目" clearable>
            <el-option
              v-for="item in projectTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">筛选</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 对比表格 -->
    <div class="compare-table">
      <el-table :data="tableData" border style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column prop="field" label="字段" width="150" align="center"></el-table-column>
        <el-table-column prop="value1" label="竞品项目" min-width="300" align="left"></el-table-column>
        <el-table-column prop="value2" label="我方项目" min-width="300" align="left"></el-table-column>
        <el-table-column prop="advantage1" label="与竞品对比" min-width="250" align="left">
          <template slot-scope="scope">
            <span :class="getAdvantageClass(scope.row.advantage1)">{{ scope.row.advantage1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="advantage2" label="对比说明" min-width="250" align="left">
          <template slot-scope="scope">
            <span>{{ scope.row.advantage2 }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import comparisonData from './数据对比.json'

export default {
  name: 'DataTable',
  data() {
    return {
      filterForm: {
        province: '',
        city: '',
        district: '',
        companyType: '',
        projectType: ''
      },
      // 省份数据
      provinces: [
        { value: 'guangdong', label: '广东省' },
        { value: 'shanghai', label: '上海市' },
        { value: 'beijing', label: '北京市' }
      ],
      // 城市数据
      citiesMap: {
        guangdong: [
          { value: 'shenzhen', label: '深圳市' },
          { value: 'guangzhou', label: '广州市' },
          { value: 'dongguan', label: '东莞市' }
        ],
        shanghai: [
          { value: 'pudong', label: '浦东新区' },
          { value: 'huangpu', label: '黄浦区' },
          { value: 'jingan', label: '静安区' }
        ],
        beijing: [
          { value: 'chaoyang', label: '朝阳区' },
          { value: 'haidian', label: '海淀区' }
        ]
      },
      // 区县数据
      districtsMap: {
        shenzhen: [
          { value: 'nanshan', label: '南山区' },
          { value: 'futian', label: '福田区' },
          { value: 'luohu', label: '罗湖区' },
          { value: 'baoan', label: '宝安区' },
          { value: 'longgang', label: '龙岗区' }
        ],
        guangzhou: [
          { value: 'tianhe', label: '天河区' },
          { value: 'yuexiu', label: '越秀区' },
          { value: 'haizhu', label: '海珠区' },
          { value: 'liwan', label: '荔湾区' }
        ]
      },
      // 竞品名称数据
      companyTypes: [
        { value: 'company1', label: '新春广厦' },
        { value: 'company2', label: '中德企业' },
        { value: 'company3', label: '光谷产业园' }
      ],
      // 竞品项目数据
      projectTypes: [
        { value: 'type1', label: '独栋厂房' },
        { value: 'type2', label: '双拼厂房' },
        { value: 'type3', label: '高层办公' },
        { value: 'type4', label: '研发中心' }
      ],
      cities: [],
      districts: [],
      // 初始表格数据为空
      tableData: [],
      // JSON数据
      comparisonData: comparisonData
    }
  },
  methods: {
    // 省份切换处理
    handleProvinceChange(value) {
      // 重置城市和区县
      this.filterForm.city = ''
      this.filterForm.district = ''
      this.filterForm.companyType = ''
      this.filterForm.projectType = ''
      this.districts = []
      this.cities = value ? this.citiesMap[value] || [] : []
      // 清空表格数据
      this.tableData = []
    },
    // 城市切换处理
    handleCityChange(value) {
      // 重置区县
      this.filterForm.district = ''
      this.filterForm.companyType = ''
      this.filterForm.projectType = ''
      this.districts = value ? this.districtsMap[value] || [] : []
      // 清空表格数据
      this.tableData = []
    },
    // 区县切换处理
    handleDistrictChange() {
      this.filterForm.companyType = ''
      this.filterForm.projectType = ''
      // 清空表格数据
      this.tableData = []
    },
    // 竞品名称切换处理
    handleCompanyTypeChange() {
      this.filterForm.projectType = ''
      // 清空表格数据
      this.tableData = []
    },
    // 根据winner字段生成胜出方文本（仅显示输赢）
    getWinnerText(winner) {
      if (!winner) return ''
      
      if (winner === '竞品') {
        return '胜出方：竞品'
      } else if (winner === '我司') {
        return '胜出方：我司'
      } else if (winner === '平局') {
        return '平局'
      }
      return ''
    },
    // 获取原因说明文本（不包含winner信息）
    getReasonText(reason) {
      return reason || ''
    },
    // 将JSON数据转换为表格格式
    convertJsonToTableData() {
      if (!this.comparisonData || !this.comparisonData.comparison_results) {
        return []
      }

      const results = this.comparisonData.comparison_results
      const tableRows = []

      // 地段维度
      if (results.location) {
        const location = results.location
        const traffic = location.analysis?.traffic_comparison
        const facilities = location.analysis?.supporting_facilities_comparison
        const industry = location.analysis?.industry_comparison

        if (traffic) {
          tableRows.push({
            field: '交通便利性',
            value1: traffic.competitor_traffic || '',
            value2: traffic.our_traffic || '',
            advantage1: this.getWinnerText(traffic.winner),
            advantage2: this.getReasonText(traffic.reason)
          })
        }

        if (facilities) {
          tableRows.push({
            field: '生活配套',
            value1: facilities.competitor_facilities || '',
            value2: facilities.our_facilities || '',
            advantage1: this.getWinnerText(facilities.winner),
            advantage2: this.getReasonText(facilities.reason)
          })
        }

        if (industry) {
          tableRows.push({
            field: '产业配套',
            value1: industry.competitor_industry || '',
            value2: industry.our_industry || '',
            advantage1: this.getWinnerText(industry.winner),
            advantage2: this.getReasonText(industry.reason)
          })
        }
      }

      // 产品维度
      if (results.product) {
        const product = results.product
        const productRichness = product.analysis?.product_richness_comparison
        const productDetails = product.analysis?.product_details

        if (productRichness) {
          tableRows.push({
            field: '产品丰富度',
            value1: `产品类型：${productRichness.competitor_products?.join('、') || ''}`,
            value2: `产品类型：${productRichness.our_products?.join('、') || ''}`,
            advantage1: this.getWinnerText(productRichness.winner),
            advantage2: this.getReasonText(productRichness.reason)
          })
        }

        if (productDetails && Array.isArray(productDetails)) {
          productDetails.forEach(detail => {
            const comp = detail.comparison
            if (comp) {
              tableRows.push({
                field: `${detail.product_type} - 层高`,
                value1: `层数：${detail.competitor_data?.floor_count || ''}，层高：${detail.competitor_data?.floor_height || ''}`,
                value2: `层数：${detail.our_data?.floor_count || ''}，层高：${detail.our_data?.floor_height || ''}`,
                advantage1: this.getWinnerText(comp.floor_height_winner),
                advantage2: this.getReasonText(comp.floor_height_reason)
              })

              tableRows.push({
                field: `${detail.product_type} - 承重`,
                value1: `承重：${detail.competitor_data?.bear_weight || detail.competitor_data?.bearing || ''}`,
                value2: `承重：${detail.our_data?.bearing || ''}`,
                advantage1: this.getWinnerText(comp.bearing_winner),
                advantage2: this.getReasonText(comp.bearing_reason)
              })

              tableRows.push({
                field: `${detail.product_type} - 面积段`,
                value1: `面积：${detail.competitor_data?.area_part || detail.competitor_data?.area_range || ''}`,
                value2: `面积：${detail.our_data?.area_range || ''}`,
                advantage1: this.getWinnerText(comp.area_range_winner),
                advantage2: this.getReasonText(comp.area_range_reason)
              })
            }
          })
        }
      }

      // 价格维度
      if (results.price) {
        const price = results.price
        const priceComparison = price.analysis?.price_comparison

        if (priceComparison && Array.isArray(priceComparison)) {
          priceComparison.forEach(item => {
            tableRows.push({
              field: `${item.product_type} - 价格`,
              value1: item.competitor_price || '',
              value2: item.our_price || '',
              advantage1: this.getWinnerText(item.winner),
              advantage2: this.getReasonText(item.reason)
            })
          })
        }
      }

      // 阶段维度
      if (results.stage) {
        const stage = results.stage
        const stageComparison = stage.analysis?.stage_comparison

        if (stageComparison) {
          tableRows.push({
            field: '工程进度',
            value1: stageComparison.competitor_stage_detail || '',
            value2: stageComparison.our_stage_detail || '',
            advantage1: this.getWinnerText(stageComparison.winner),
            advantage2: this.getReasonText(stageComparison.reason)
          })
        }
      }

      // 品牌维度
      if (results.brand) {
        const brand = results.brand
        const brandComparison = brand.analysis?.brand_comparison

        if (brandComparison) {
          tableRows.push({
            field: '品牌等级',
            value1: `${brandComparison.competitor_brand}（等级${brandComparison.competitor_level}）`,
            value2: `${brandComparison.our_brand}（等级${brandComparison.our_level}）`,
            advantage1: this.getWinnerText(brandComparison.winner),
            advantage2: this.getReasonText(brandComparison.reason)
          })
        }
      }

      // 团队维度
      if (results.team) {
        const team = results.team
        const teamComparison = team.analysis?.team_comparison

        if (teamComparison) {
          tableRows.push({
            field: '团队配置',
            value1: teamComparison.competitor_team?.config || '无数据',
            value2: teamComparison.our_team?.config || '',
            advantage1: this.getWinnerText(teamComparison.winner),
            advantage2: this.getReasonText(teamComparison.reason)
          })
        }
      }

      // 准入维度
      if (results.access) {
        const access = results.access
        const taxComparison = access.analysis?.tax_comparison
        const industryComparison = access.analysis?.industry_comparison

        if (taxComparison) {
          tableRows.push({
            field: '税收要求',
            value1: taxComparison.competitor_tax || '无',
            value2: taxComparison.our_tax || '',
            advantage1: this.getWinnerText(taxComparison.winner),
            advantage2: this.getReasonText(taxComparison.reason)
          })
        }

        if (industryComparison) {
          tableRows.push({
            field: '行业要求',
            value1: industryComparison.competitor_industry_requirements || '无',
            value2: industryComparison.our_industry_requirements || '',
            advantage1: this.getWinnerText(industryComparison.winner),
            advantage2: this.getReasonText(industryComparison.reason)
          })
        }
      }

      return tableRows
    },
    // 搜索处理
    handleSearch() {
      const { province, city, district, companyType, projectType } = this.filterForm
      
      // 只有当所有条件都选择后才查询数据
      if (province && city && district && companyType && projectType) {
        // 从JSON数据转换表格数据
        const convertedData = this.convertJsonToTableData()
        
        // 更新表格数据
        this.tableData = convertedData
      } else {
        // 如果条件不完整，清空表格数据
        this.tableData = []
      }
    },
    // 设置表格行的类名
    tableRowClassName({ row }) {
      const specialFields = ['区位', '总体量', '产品', '工程进度', '价格']
      return specialFields.includes(row.field) ? 'highlight-row' : ''
    },
    // 获取优势/劣势的样式类名
    getAdvantageClass(text) {
      if (!text) return 'neutral-text'
      
      // 识别胜出方：我司（优势）
      if (text.includes('胜出方：我司')) {
        return 'advantage-text'
      } 
      // 识别胜出方：竞品（劣势）
      else if (text.includes('胜出方：竞品')) {
        return 'disadvantage-text'
      }
      // 识别平局
      else if (text.includes('平局')) {
        return 'neutral-text'
      }
      // 兼容旧格式
      else if (text.includes('我方优势')) {
        return 'advantage-text'
      } else if (text.includes('我方劣势')) {
        return 'disadvantage-text'
      }
      
      return 'neutral-text'
    }
  }
}
</script>

<style lang="less" scoped>
.data-table {
  padding: 20px;

  .filter-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;

    .filter-form {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 20px;
      }
    }
  }

  .compare-table {
    background: #fff;
    padding: 20px;
    border-radius: 4px;

    // 当表格无数据时的提示样式
    .el-table__empty-block {
      min-height: 200px;
      .el-table__empty-text {
        color: #909399;
        font-size: 14px;
      }
    }

    // 表格样式
    /deep/ .el-table {
      // 表头样式
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: bold;
        height: 50px;
      }

      // 单元格样式
      td {
        padding: 12px 0;
      }

      // 字段列样式
      .el-table__row td:first-child {
        font-weight: bold;
        color: #606266;
      }

      // 高亮行样式
      .highlight-row {
        background-color: #fdf6ec;
        td {
          font-weight: bold;
        }
      }

      // 对比列样式
      td:nth-child(4), td:nth-child(5) {
        font-size: 13px;
        line-height: 1.4;
      }

      // 优势劣势文字样式
      .advantage-text {
        color: #67C23A;
        font-weight: 500;
      }
      
      .disadvantage-text {
        color: #F56C6C;
        font-weight: 500;
      }
      
      .neutral-text {
        color: #606266;
      }

      // 表格边框
      border: 1px solid #EBEEF5;
      td, th {
        border-right: 1px solid #EBEEF5;
        border-bottom: 1px solid #EBEEF5;
      }
    }
  }
}
</style>
